<?php

namespace app\admin\service\statistics\promotion;

use app\admin\service\statistics\completions\Completion;

/**
 * 统计器 计算统计 抽象基类
 * Class AbstractComputeStatistician
 * @package app\admin\service\statistics\promotion
 */
abstract class AbstractComputeStatistician implements Statistician
{
    // 前置数据
    protected array $statisticians = [];

    // 补齐
    protected array $completions = [];

    public function setStatisticiansMap(array $statisticians): self
    {
        $this->statisticians = $statisticians;

        return $this;
    }

    public function setCompletions(Completion ...$completions): self
    {
        foreach ($completions as $completion) {
            $this->completions[] = $completion;
        }

        return $this;
    }

    /**
     * 获取数据
     * @return array
     */
    public function getData(): array
    {
        $array = [];

        // 调用数据补齐
        foreach ($this->completions as $completion) {
            $className = get_class_name($completion);
            $methodName = 'completionBy' . $className;
            if (method_exists($this, $methodName)) {
                $array = $this->$methodName($array, $completion);
            }
        }

        // 计算
        foreach ($array as $index => $item){
            $array[$index]['value'] = $this->compute($index);
        }

        return $array;
    }

    /**
     * 数据计算
     * @param int $index
     * @return mixed
     */
    abstract protected function compute(int $index);

}